package com.logic.modular.gameCore.cultivate.hero.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.comment.pojo.domain.logic.core.CoreHero;
import lombok.extern.slf4j.Slf4j;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.logic.modular.gameCore.cultivate.hero.mapper.CoreHeroMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import static com.logic.modular.gameCore.CoreCacheInfo.infoCache;


/**
 * 武将基础数据表(CoreHero)表服务实现类
 *
 * @author cxy
 * @since 2024-08-05 16:14:02
 */
@Slf4j
@Service
public class CoreHeroServiceImpl extends ServiceImpl<CoreHeroMapper, CoreHero>
        implements IService<CoreHero>, CoreHeroService {
    private static final Cache<String, Map<Long, CoreHero>> cache = Caffeine.newBuilder().build();
    @Resource
    private CoreHeroMapper coreHeroMapper;

    @PostConstruct
    private void init() {
        CoreHero initSelect = CoreHero.builder().build();
        List<CoreHero> list = this.list(new LambdaQueryWrapper<>(initSelect));
        log.info("开始缓存武将基础数据表数据,数据量为:{}", list.size());
        cache.put(
                "coreHero",
                list.stream().collect(Collectors.toMap(CoreHero::getId, CoreHero -> CoreHero))
        );
        log.info("武将基础数据表数据缓存完成");
    }

    public static List<CoreHero> listCache() {
        Map<Long, CoreHero> values = cache.getIfPresent("coreHero");
        if (Objects.isNull(values)) {
            throw new RuntimeException("武将基础数据表数据为空");
        }
        return new ArrayList<>(values.values());
    }

    public Map<Long, CoreHero> mapCache() {
        Map<Long, CoreHero> values = cache.getIfPresent("coreHero");
        if (Objects.isNull(values)) {
            throw new RuntimeException("武将基础数据表数据为空");
        }
        return values;
    }

    public static CoreHero getCache(Long id) {
        Map<Long, CoreHero> values = cache.getIfPresent("coreHero");
        if (Objects.isNull(values)) {
            throw new RuntimeException("武将基础数据表数据为空");
        }
        return values.get(id);
    }

    @Override
    public Integer getHeroMaxQualityLv() {
        String key = String.format("%s:", "heroMaxQualityLv");
        Integer heroMaxQualityLv = (Integer) infoCache.getIfPresent(key);
        if (heroMaxQualityLv == null) {
            heroMaxQualityLv = coreHeroMapper.getHeroMaxQualityLv();
            infoCache.put(key, heroMaxQualityLv);
        }
        return heroMaxQualityLv;
    }
}
